<template>
  <div class="app-container chip-box">
    <el-form :inline="true" label-width="68px" style="margin-bottom: 15px;">
      <el-form-item label="物料编码">
        <el-input v-model="searchForm.searchCode" clearable  size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input v-model="searchForm.searchName" clearable size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="serchReset()">重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-menu" size="mini" @click="checkleAll">查询所有</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-select v-model="selectwarehouse" placeholder="零头仓库" @change="warehouseChange">
          <el-option v-for="item in optionswarehouse" :key="item.uniqueId" :label="item.name" :value="item.code">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" :class="{'is-plan':queryParams.flag==1}" size="mini"
          @click="handleRecovery('recycled')">待回收</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" :class="{'is-plan':queryParams.flag==0}" size="mini"
          @click="handleRecovery('success')">已回收</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>
    <!-- 物料数据 -->
    <div class="inv-box">
      <el-form ref="formInput" :model="formInput" :rules="rules">
        <el-table :data="formInput.chipList" border :height="maxHeight" v-loading="loading" ref="table"
          :key="Math.random()" :row-class-name="tableRowClassName" @row-dblclick="handleView">
          <el-table-column type="index" width="60" align="center" label="序号">
          </el-table-column>
          <el-table-column label="出库单号" align="center" prop="wmCode">
          </el-table-column>
          <el-table-column label="设备" align="center" prop="productionLine">
            <template slot-scope="scope">
              <div>
                <span>{{scope.row.deptName}}&nbsp;&nbsp;{{scope.row.productionLine}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="物料编码" align="center" prop="invCode">
          </el-table-column>
          <el-table-column label="物料名称" align="center" prop="invName">
          </el-table-column>
          <el-table-column label="型号规格" align="center" prop="invAttribute">
          </el-table-column>
          <el-table-column label="计量单位" align="center" prop="unitName" width="45">
          </el-table-column>
          <el-table-column label="属性" align="center">
            <template slot-scope="scope">
              <div>
                <span>{{scope.row.f1}}{{scope.row.f2}}{{scope.row.f3}}{{scope.row.f4}}{{scope.row.f5}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="零头数量" align="center" prop="chipQuantity" width="150">
            <template slot-scope="scope">
              <div style="text-align: right;margin-right:10px;">
                <span>{{scope.row.chipQuantity}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="收回零头" align="center" prop="chipReturn" width="150">
            <template slot-scope="scope">
              <el-form-item class="text-right" :prop=" 'chipList.' + scope.$index + '.chipReturn' "
                :rules='rules.chipReturn' :class="{'is-error':scope.row.borderStatus}">
                <el-input v-model="scope.row.chipReturn" style="text-align: right;"
                  @input="formatDecimal(scope.$index,scope.row)" :disabled="queryParams.flag==1">
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="收回备注" align="center" prop="chipRemark" width="150">
            <template slot-scope="scope">
              <el-form-item :prop=" 'chipList.' + scope.$index + '.chipRemark' " :rules='rules.chipRemark'>
                <el-input v-model="scope.row.chipRemark" style="text-align: right;"
                  @input="formatDecimal(scope.$index,scope.row)" :disabled="queryParams.flag==1">
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding" width="150" v-if="queryParams.flag==0">
            <template slot-scope="scope">
              <div class="public-btn">
                <el-button size="mini" :disabled="!scope.row.light" type="text" class="basic-see"
                  @click.stop="handleUpdate(scope.$index,scope.row)">保存
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

    </div>
    <!-- 分页信息 -->
    <pagination v-if="formInput.chipList.length>0&&total>21" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getChipList()" />

  </div>
</template>

<script>
  import {
    getToken
  } from "@/utils/auth";
  import {
    listWarehouses,
    listChip,
    updateChip,
    exportChip
  } from "../../api/chip";
  import axios from 'axios';
  //输入是否为数字效验
  import {
    isAccord
  } from "@/utils/cingsoft"
  export default {
    name: "Chip",
    data() {
      // 数量输入效验
      var checkchipReturn = (rule, value, callback) => {
        if (value == null || value == "") {
          callback();
        } else if (!isAccord(value)) {
          callback(new Error(''));
        } else {
          callback();
        }
      };
      return {
        loading: true,
        searchForm: {
          searchCode: "",
          searchName: "",
        },
        //当前数据index
        upadtateIndex: "",
        //仓库选择
        optionswarehouse: [],
        selectwarehouse: "",
        // 物料查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 100,
          flag: 0
        },
        //物料数据
        formInput: {
          chipList: []
        },
        //物料数据最大高度
        maxHeight: null,
        rules: {
          chipReturn: [{
            validator: checkchipReturn,
            trigger: 'blur'
          }],
        }
      };
    },
    created() {
      this.getHouselList()
    },
    methods: {
      //仓库列表
      getHouselList() {
        listWarehouses({
          invoiceType: "",
          bredVouch: "",
          workType: ""
        }).then(res => {
          if (res.code == 200) {
            this.optionswarehouse = res.rows;
            if (this.optionswarehouse.length > 0) {
              this.warehouseChange(this.optionswarehouse[0].code);
              this.selectwarehouse = this.optionswarehouse[0].code;
            } else {
              this.loading = false;
            }
          }
        })
      },

      /*  仓库选择 */
      warehouseChange(code) {
        // 清空入库单据搜索
        this.searchFrom = {
          searchCode: "",
          searchName: "",
        };
        this.queryParams.warehouse = code;
        this.getChipList()
      },
      //零头列表
      getChipList() {
        this.loading = true;
        this.formInput.chipList = [];
        listChip(this.queryParams).then(res => {
          if (res.code == 200) {
            const list = JSON.parse(JSON.stringify(res.rows));
            list.forEach(obj => {
              obj.borderStatus = false;
            })
            this.formInput.chipList = list;
            this.total = res.total;
            if (this.formInput.chipList.length >= 19) { //条数总数大于显示出现滚动条
              this.maxHeight = (`${document.documentElement.clientHeight}` - 270);
            } else {
              this.maxHeight = null;
            }
            this.loading = false;
          }
        })
      },

      //搜索物料
      search() {
        if (this.searchForm.searchName == "" && this.searchForm.searchCode == "") {
          this.msgError("物料编码或物料名称不能同时为空！");
        } else {
          this.queryParams.invName = this.searchForm.searchName; //赋值物料名称
          this.queryParams.invCode = this.searchForm.searchCode; //赋值物料编码
          this.getChipList();
        }

      },
      // 查询所有
      checkleAll() {
        //清空搜索信息，避免干扰
        this.queryParams.invName = "";
        this.queryParams.invCode = "";
        this.serchReset(); //重置搜索表单
        this.getChipList()
      },

      //搜索表单重置
      serchReset() {
        for (let key in this.searchForm) {
          this.searchForm[key] = ""
        }
      },

      //待回收已回收切换
      handleRecovery(type) {
        if (type == 'recycled') {
          this.queryParams.flag = 0;
          this.getChipList()
        } else {
          this.queryParams.flag = 1;
          this.getChipList()
        }
      },
      // 格式化用户输入价格单价小数位数
      formatDecimal(index, data) {
        if ((data.chipReturn > data.chipQuantity)) {
          data.borderStatus = true; //改变输入框状态
        } else if (isAccord(data.chipReturn) && data.chipReturn > 0) {
          this.upadtateIndex = index;
          data.light = true;
          data.borderStatus = false; //改变输入框状态
        } else {
          this.upadtateIndex = "";
          data.light = false;
          data.borderStatus = false; //改变输入框状态
        }

      },

      //保存
      handleUpdate(index, data) {
        this.$refs['formInput'].validate((valid) => {
          if (valid) {
            data.chipDate = this.chipDate();
            updateChip(data).then(res => { //触发保存提交
              if (res.code == 200) {
                this.formInput.chipList[index].chipReturn = res.data.chipReturn;
                this.formInput.chipList[index].chipRemark = res.data.chipRemark;
                this.upadtateIndex = "";
                data.light = false;
                this.msgSuccess("保存成功")
              }
            }).catch(err => {
              this.msgError("保存失败");
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      /* 复制表格变色 */
      tableRowClassName({
        row,
        rowIndex
      }) {
        if (row.background === true) {
          return 'light-row';
        }
        return '';
      },

      //导出
      handleExport() {
        let queryParams = this.queryParams,
          title = "";
        if (queryParams.flag == 0) {
          title = "待回收";
        } else {
          title = "已回收";
        }
        this.$confirm(`是否确认导出${title}零头数据项?`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportChip(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      // 双击查看物料
      handleView(row) {
        this.$router.push({
          path: `/wm/stock/checkoutview`,
          query: {
            detailCode: row.wmCode,
            open: "seeStatus",
            whCode: this.selectwarehouse,
            bredVouch: "",
            invoiceType: "",
            workType: ""
          }
        })
      },
      chipDate() {
        let time = new Date();
        return time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate() + " " + time.getHours() + ":" +
          time.getMinutes() + ":" + time.getSeconds()
      }
    },

  }
</script>
<style lang="scss">
  .chip-box {
    .el-table__body tr.current-row>td {
      background-color: #F5F7FA !important;
    }

    .el-select {
      input {
        line-height: 28px;
        height: 28px;
        width: 150px;
      }
    }

    .is-plan {
      border-color: #badeff;
      background-color: #e8f4ff;
      color: #1890ff;
    }

    .el-table tr {
      cursor: pointer;
      user-select: none;
    }

    .text-right {
      input {
        text-align: right !important;
      }

      span {
        display: inline-block;
        padding-right: 10px;
        width: 100%;
        text-align: right;
      }
    }

    .el-table .light-row {
      background-color: #F5F7FA;
    }

    .public-btn .is-disabled span {
      opacity: .5;
    }

    .el-input--medium .el-input__icon {
      line-height: 28px;
    }

    .el-form-item--medium .el-form-item__content {
      margin-right: 10px;
    }

    .el-table--border th:first-child .cell,
    .el-table--border td:first-child .cell {
      padding-left: 0;
    }


    .inv-box {
      .el-input__inner {
        height: 31px;
        line-height: 0;
        color: #606266;
        background: none;
        border-color: #fff;
        border-radius: 0;
        padding: 0;
        text-align: center;
      }

      .cell button {
        padding: 0;
      }

      .el-form-item__content {
        line-height: 30px;
      }

      .el-form-item {
        margin-bottom: 0;
      }

      .el-table--medium td {
        padding: 0 !important;
      }

      .cell {
        height: auto !important;
        line-height: 30px;
        padding-left: 0;
        padding-right: 0;
      }

      // .el-table--enable-row-hover .el-table__body tr:hover>td {
      //   background: none;
      // }

      .el-form-item.is-error .el-input__inner,
      .el-form-item.is-error .el-input__inner:focus,
      .el-form-item.is-error .el-textarea__inner,
      .el-form-item.is-error .el-textarea__inner:focus {
        border-color: #ff4949;
      }

      .con-spec {
        display: flex;
        text-align: center;
        justify-content: center;
        word-wrap: break-word;
      }

      .el-table--medium th,
      .el-table--medium td {
        padding: 0 !important;
        text-align: center;
      }

    }

  }
</style>
